package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.kh.LogToDB
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.swing.text.Document

/**
 * @projectName: 德高
 * @className: apiSendMSGNOTE
 * @author: Rick
 * @description: 短信发送失败消息通知
 * @date: 2023-03-12 15:03
 * @version: 1.0
 */
public class apiSendMSGNOTE implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiSendMSGNOTE.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        JSONObject resultJson = new JSONObject();
        resultJson.put("errcode", 0);
        resultJson.put("errmsg", "");
        resultJson.put("msgid", "");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            resultJson.put("errcode", -2);
            resultJson.put("errmsg", "API被非法IP调用-Request Not Allow!");
            return resultJson.toString();
        }

        //扫描短信发送表，所有短信发送失败的数据
        String DocumentFileSQL='''select d.Documentout_Guid,d.CreatedBy,s.StaffName,
                                    d.DocumentTo,
                                    CASE WHEN d.FailCode=-1 THEN d.FailDescription 
                                        WHEN d.Report_Status='FAIL' THEN d.Error_Detail 
                                        else '超时未发送' END AS ERROR_MSG ,
                                        DocumentPath
                                        from  documentout d
                                        left join staff s on d.CreatedBy=s.staff_id
                                        where d.DocType=3 
                                        and d.passflag is null
                                        and (
                                                (
                                                 d.FailCode = -1
                                                  OR
                                                 d.Report_Status = 'FAIL'
                                                 ) 
                                                 OR 
                                                 (
                                                  d.TrialCount=0 
                                                   and 
                                                  d.CreatedDate<DATE_SUB(NOW(),INTERVAL 5 MINUTE)
                                                  )
                                                ) 
                                             '''

        List DocumentFileList = eliteBean.chaxun_sql(DocumentFileSQL.toString(), "dataSource");
        String DocumentTo="";
        String CreatedBy="";
        String ERROR_MSG="";
        String Documentout_Guid="";
        String DocumentPath="";
        String StaffName="";
        String SendClose="";
         for (int i = 0; i < DocumentFileList.size(); i++) {
             Documentout_Guid = DocumentFileList.get(i).get("Documentout_Guid");
             DocumentTo = DocumentFileList.get(i).get("DocumentTo");
             CreatedBy = DocumentFileList.get(i).get("CreatedBy");
             ERROR_MSG = DocumentFileList.get(i).get("ERROR_MSG");
             DocumentPath = DocumentFileList.get(i).get("DocumentPath");
             StaffName=DocumentFileList.get(i).get("StaffName");
             sendMsg_Note(eliteBean, "短信发送失败："+DocumentTo, "<span style=\"color:red\">当前短信发送失败信息：</span>" + ERROR_MSG+"</br></br><span style=\"color:red\">发送内容详情：</span>"+DocumentPath, CreatedBy, StaffName, "1");

             SendClose='''update documentout set  passflag=1 where Documentout_Guid=\''''+Documentout_Guid+'''\'  '''
             eliteBean.update(SendClose.toString(), "dataSource");
         }


         LogToDB.toDB(eliteBean, "dataSource", "短信发送失败消息通知", "apiSendMSGNOTE", "定时无传参", DocumentFileList.toString(), (System.currentTimeMillis() - startTime).toString(), "/");

        resultJson.put("code", 1);
        resultJson.put("msg", "消息发送成功："+DocumentFileList.size()+"条发送失败！");
        return resultJson.toString();
    }





    /**
     * 消息便签发送
     *
     * @param Lijt
     * @return
     */

    public static boolean sendMsg_Note(EliteBean eliteBean, String Subject, String Content, String Staffid, String StaffName, String Priority) {

        String note_Guid = KHUtil.getRandomString(36);
        String Msg_Note_Staff = "Insert Into Msg_Note_Staff (Msgid, Staffid, Readtime, Flag, Replied, Deleted) Values ('" + note_Guid + "', '" + Staffid + "', Null, 0, 0, 0)";
        String Msg_Note = "Insert Into Msg_Note (Id, Subject, Priority, Receiver, Createdby, Createdtime, Deleted, Content) Values ('" + note_Guid + "', '" + Subject + "', '" + Priority + "', '" + StaffName + "', 'SELITE', Now(), 0, '" + Content + "</br></br><span style=\"color:red\">⚠本便签由系统自动发出，请勿直接回复！</span>')";
        eliteBean.update(Msg_Note_Staff, "dataSource");
        eliteBean.update(Msg_Note, "dataSource");

    }


}